<?php
/**
 * Created by PhpStorm.
 * User: daniel
 * Date: 2016/7/6
 * Time: 11:15
 */

$reg="/(\w{4,})/";
$historyFile="./history";
$outputFile="./output";
$data=file_get_contents("./input");
$historyStr=file_get_contents($historyFile);
$history=json_decode($historyStr,true);
preg_match_all($reg,$data,$match);
$words=array_unique($match[0]);
$output="";
foreach ($words as $word) {
    $word=strtolower($word);
    if(isset($history[$word]))
    {
        $translateItem= $history[$word];
        $history[$word]["count"]++;
    }else{
        $translateItem=translate_from_youdao($word);
        $history[$word]=$translateItem;
        $output.= buildTranslateStr($word,$translateItem)."\n";
    }
}
file_put_contents($outputFile,$output);
file_put_contents($historyFile,json_encode($history));

function buildTranslateStr($word,$translateItem)
{
    $str="$word  US:[%s] UK[%s]  \n\t%s";
    return  sprintf($str,
        $translateItem["uk-phonetic"],
        $translateItem["us-phonetic"],
        $translateItem["explains"]);
}
function translate_from_youdao($word){
    $url="http://fanyi.youdao.com/openapi.do?keyfrom=MyTestFanyi&key=1865569157&type=data&doctype=json&version=1.1&q=$word";
    $resultStr=file_get_contents($url);
    $result=json_decode($resultStr,true);
    if($result)
    {
        if($result["errorCode"]==0)
        {
            $item["uk-phonetic"]=isset($result["basic"]["uk-phonetic"])?$result["basic"]["uk-phonetic"]:"";
            $item["us-phonetic"]=isset($result["basic"]["us-phonetic"])?$result["basic"]["us-phonetic"]:"";
            if(isset($result["basic"]["explains"])&&$result["basic"]["explains"])
            {
                $item["explains"]=implode("\n\t",$result["basic"]["explains"]);
            }
            $item["count"]=1;
            return $item;
        }else{
            echo "parse $word error.Code is ".$result["errorCode"];
        }
    }else{
        return false;
    }

}

